package com.bort.system.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.*;

public class HttpClientUtils {

    public static String httpGetParamsJson(String url,Map<String,Object> params){

        CloseableHttpClient client = HttpClients.createDefault();
        HttpGetWithEntity requestEntity = new HttpGetWithEntity(url);
        requestEntity.setHeader("Content-Type", "application/json");
        requestEntity.setHeader( "User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)" );
        requestEntity.setHeader( "Date", DateUtils.toStrTime(new Date()));
        HttpEntity httpEntity = new StringEntity(JSONObject.toJSONString(params), ContentType.APPLICATION_JSON);
        requestEntity.setEntity(httpEntity);

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = null;
        try {
            response = client.execute(requestEntity);

            int STATUS_CODE = response.getStatusLine().getStatusCode();
            if(STATUS_CODE ==  HttpStatus.SC_OK){
                HttpEntity responseEntity = response.getEntity();
                String result = EntityUtils.toString(responseEntity);
                EntityUtils.consume(responseEntity);
                return result;
            }else{
                System.out.println("http错误码:"+STATUS_CODE);
                return null;
            }
            //释放链接
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getRequest(String url,Map<String,Object> param) {

        try {
            CloseableHttpClient client = HttpClients.createDefault();

            // 构建带参数的URL
            URIBuilder builder = new URIBuilder(url);
            Iterator<String> keyItr = param.keySet().iterator();
            while (keyItr.hasNext()){
                String key = keyItr.next();
                String value = param.get(key) != null?param.get(key).toString():null;
                builder.addParameter(key,value);
            }
            HttpGet request = new HttpGet(builder.build());

            // 执行请求
            CloseableHttpResponse response = client.execute(request);

            // 获取响应实体
            String result = EntityUtils.toString(response.getEntity());
            response.close();
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 发送form表单类型的Post请求
     *
     * @param url       发送的url
     * @param headerMap 请求头参数集合 key参数名 value为参数值
     * @param bodyMap   请求参数集合 key参数名 value为参数值
     */
    public static String sendFormPost(String url, Map<String, String> headerMap, Map<String, String> bodyMap) {

        //创建post请求对象
        HttpPost post = new HttpPost(url);
        try {
            //创建参数集合
            List<BasicNameValuePair> list = new ArrayList<>();
            //添加参数
            if (bodyMap != null) {
                for (String str : bodyMap.keySet()
                ) {
                    list.add(new BasicNameValuePair(str, bodyMap.get(str)));
                }
            }
            //把参数放入请求对象，，post发送的参数list，指定格式
            post.setEntity(new UrlEncodedFormEntity(list, Charset.forName("UTF-8")));

            return sendPost(post,headerMap);
        } catch (Exception e1) {
            e1.printStackTrace();
            return "";
        }
    }

    public static String sendPostWithJson(String url,Map<String,String> headerMap, Map<String, Object> params) {
        HttpPost httpPost = new HttpPost(url);
        try {
            if (params != null) {
                StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params), "UTF-8");
                stringEntity.setContentType("application/json;charset=utf-8");
                httpPost.setEntity(stringEntity);
            }
            return sendPost(httpPost,headerMap);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private static String sendPost(HttpPost post,Map<String,String> headerMap) throws Exception {
        if (headerMap != null) {
            for (String str : headerMap.keySet()
            ) {
                post.addHeader(str, headerMap.get(str));
            }
        }

        CloseableHttpClient client = HttpClients.createDefault();
        //启动执行请求，并获得返回值
        CloseableHttpResponse response = client.execute(post);
        //得到返回的entity对象
        HttpEntity entity = response.getEntity();
        //把实体对象转换为string
        String result = EntityUtils.toString(entity,  Charset.forName("UTF-8"));
        //为防止频繁调用一个接口导致接口爆掉，每次调用完成后停留100毫秒
        Thread.sleep(100);
        //返回内容
        return result;
    }

}
